<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
        <!--供货商数据-->
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="90px" v-show="showSearch" >
          <el-form-item label="防伪码" prop="trackingCode">
            <el-input v-model="queryParams.trackingCode" placeholder="请输入防伪码" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="批次号" prop="trackingBatch">
            <el-input v-model="queryParams.trackingBatch" placeholder="请输入批次号" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="物流码" prop="transportCode">
            <el-input v-model="queryParams.transportCode" placeholder="请输入物流码" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="供货商" prop="supplierName">
            <el-input v-model="queryParams.supplierName" placeholder="请输入供货商" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="启用状态" prop="statusCode">
            <el-select @change="handleQuery" v-model="queryParams.statusCode" size="small" clearable style="width: 150px" placeholder="请选择">
              <el-option key="" label="全部" value=""/>
              <el-option v-for="item in statusOptions" :key="item.dictCode" :label="item.dictName" :value="item.dictCode"/>
            </el-select>
          </el-form-item>

          <el-form-item label="产品名称" prop="productName">
            <el-input v-model="queryParams.productName" placeholder="请输入产品名称" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker @change="handleQuery" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
          </el-form-item>

          <el-form-item>
            <el-button type="primary"  size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" v-hasPermi="['saveTrackingCode']"   icon="el-icon-plus" size="mini" @click="handleAdd(false)">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" v-hasPermi="['updateTrackingCode']"  icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" v-hasPermi="['deleteTrackingCode']"  icon="el-icon-delete" size="mini" :disabled="single" @click="handleDelete">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" v-hasPermi="['batchSaveTrackingCode']"  icon="el-icon-folder-add" size="mini" @click="handleAdd(true)">批量新增防伪码</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="queryTrackingCodePageResList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table ref="multipleTable" :stripe="true" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
                  @sort-change='tableSortChange' :default-sort="{prop: 'sort', order: 'descending'}">
          <el-table-column type="selection" align="center"/>
          <el-table-column label="防伪码" align="left" prop="trackingCode">
            <template slot-scope="scope">
              <el-tooltip content="点击下载二维码" placement="top-start" v-if="scope.row.trackingCodeUrl">
              <span @click="downloadQrCodeImg(scope.row.trackingCode)">
                <vue-qr :text="scope.row.trackingCodeUrl" :ref="'Qrcode' + scope.row.trackingCode" :margin=" 0" colorLight="#fff" :logoScale="0.3" :size="150"></vue-qr>
                <br>
                <span>{{ scope.row.trackingCode }}</span>
              </span>
              </el-tooltip>
              <span  v-if="!scope.row.trackingCodeUrl">{{scope.row.trackingCode}}</span>
            </template>
          </el-table-column>
          <el-table-column label="批次号" align="left" prop="trackingBatch" width="200" />
          <el-table-column label="物流码" align="left" prop="transportCode" width="200" />
          <el-table-column label="供货商" align="left" prop="supplierName" width="200" />
          <el-table-column label="产品名称" align="left" prop="productName" width="200" />
          <el-table-column label="创建时间" align="left" prop="createTime" sortable='custom' width="200" />
          <el-table-column label="启用状态" align="left" prop="statusName" width="150" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.statusColor">{{scope.row.statusName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" v-hasPermi="['updateTrackingCode']" icon="el-icon-edit"  @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" type="text" v-hasPermi="['deleteTrackingCode']" icon="el-icon-delete"  @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows"
                    @pagination="queryTrackingCodePageResList"/>
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="addUpdateOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="addUpdateOpenRules"  label-width="100px">
        <el-form-item label="防伪码" prop="trackingCode" v-if="!batchSaveTracking&&form.trackingCodeId ===undefined"  :rules="{required: true, message: '防伪码必须填写'}">
          <el-input autocomplete="off" v-model="form.trackingCode" placeholder="请输入防伪码" maxlength="50" />
        </el-form-item>

        <el-form-item label="批次号" prop="trackingBatch">
          <el-input autocomplete="off" v-model="form.trackingBatch" placeholder="请输入批次号" maxlength="30" />
        </el-form-item>

        <el-form-item label="物流码" prop="transportCode">
          <el-input autocomplete="off" v-model="form.transportCode" placeholder="请输入物流码" maxlength="30" />
        </el-form-item>

        <el-form-item label="供货商" prop="supplierId">
          <el-select :hide-required-asterisk="true" v-model="form.supplierId" clearable placeholder="请选择"  style="width: 100%;">
            <el-option
              v-for="item in supplierOptions"
              :key="item.supplierId"
              :label="item.supplierName+'('+item.supplierCode+')'"
              :value="item.supplierId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所属产品" prop="productId" :rules="{required: true, message: '所属产品必须选择'}">
          <el-select :hide-required-asterisk="true" v-model="form.productId" clearable placeholder="请选择"  style="width: 100%;">
            <el-option
              v-for="item in productDataList"
              :key="item.productId"
              :label="item.productName"
              :value="item.productId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="启用状态" prop="statusCode">
          <el-select :hide-required-asterisk="true" v-model="form.statusCode" clearable placeholder="请选择"  style="width: 100%;">
            <el-option
              v-for="item in statusOptions"
              :key="item.dictCode"
              :label="item.dictName"
              :value="item.dictCode"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="生成数量" prop="batchTotal" v-if="batchSaveTracking" :rules="{required: true, message: '生成数量必须填写'}">
          <el-input-number v-model="form.batchTotal" :min="1" :max="9999"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelAddUpdateOpen">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {queryTrackingCodePageResList, saveTrackingCode, batchSaveTrackingCode, updateTrackingCode, deleteTrackingCodeByTrackingCodeId} from '@/api/tracking/trackingCode'
  import {querySelectNormalTrackingProductSupplierResList} from '@/api/tracking/trackingProductSupplier'
  import {querySelectTrackingProductPageResList} from '@/api/tracking/trackingProduct'
  import { getDicListByDictCodeList } from '@/api/common/dict'
  import VueQr from 'vue-qr'
  //默认查询参数
  let defaultQueryParams = {
    trackingCode: undefined,
    trackingBatch: undefined,
    transportCode: undefined,
    productName: undefined,
    supplierName: undefined,
    startTime: undefined,
    endTime: undefined,
    statusCode: "",
    page: 1,
    rows: 10
  }
  export default {
    name: "trackingCodeAdmin",
    components: {
      VueQr
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 显示搜索条件
        showSearch: true,
        // table表格数据
        dataList: [],
        // 日期范围
        dateRange: [],
        // 弹出层标题
        title: "",
        // 是否显示新增修改弹出层
        addUpdateOpen: false,
        //是否批量新增
        batchSaveTracking:false,
        // 状态
        statusOptions: [],
        //供货商
        supplierOptions: [],
        // 产品
        productDataList: [],
        // 增加修改表单参数
        form: {},
        // 查询参数
        queryParams: { ...defaultQueryParams },
        //列信息
        columns: [],
        // 新增修改表单校验
        addUpdateOpenRules: {
          trackingBatch: [
            { required: true, message: "批次号不能为空"},
          ],
          transportCode: [
            { required: true, message: "物流码不能为空"},
          ],
          supplierId: [
            { required: true, message: "供货商必须选择"},
          ],
          statusCode: [
            { required: true, message: "状态必须选择"}
          ]
        },
      }
    },
    created() {
      this.queryTrackingCodePageResList();
      this.initDict();
    },
    methods: {
      //获取数据字典
      initDict(){
        let dictArr = ["STATUS"];
        getDicListByDictCodeList(dictArr).then(res => {
          this.statusOptions = JSON.parse(JSON.stringify(res.data['STATUS']));
        });
      },
      //下载二维码
      downloadQrCodeImg (linkId){
        const iconUrl = (this).$refs['Qrcode' + linkId].$el.src
        const a = document.createElement('a')
        const event = new MouseEvent('click')
        a.download = linkId
        a.href = iconUrl
        a.dispatchEvent(event)
      },

      //查询产品
      querySelectTrackingProductPageResList(){
        querySelectTrackingProductPageResList({}).then(response => {
          this.productDataList = response.data.records
        })
      },

      //查询供货商
      querySelectNormalTrackingProductSupplierResList(){
        querySelectNormalTrackingProductSupplierResList({}).then(response => {
          this.supplierOptions = response.data
        })
      },
      /** 查询防伪码列表 */
      queryTrackingCodePageResList() {
        this.loading = true
        queryTrackingCodePageResList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.dataList = response.data.records
          this.total = response.data.total
          this.loading = false
        })
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.trackingCodeId)
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      //排序
      tableSortChange(column){
        //格式化排序参数，构建中
        this.orderByFormat(this.queryParams,column);
        //执行查询方法
        this.queryTrackingCodePageResList()
      },

      /*新增按钮操作 */
      handleAdd(batchSaveTracking) {
        this.reset();
        this.batchSaveTracking = batchSaveTracking;
        this.querySelectTrackingProductPageResList();
        this.querySelectNormalTrackingProductSupplierResList();
        this.addUpdateOpen = true;
        this.title = "添加防伪码";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.querySelectTrackingProductPageResList();
        this.querySelectNormalTrackingProductSupplierResList();
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        //修改表单填充
        this.form = {...row};
        this.addUpdateOpen = true;
        this.title = "修改防伪码";
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('是否确认删除所选防伪码?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const trackingCodeId={trackingCodeId:row.trackingCodeId}
          return deleteTrackingCodeByTrackingCodeId(trackingCodeId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.queryTrackingCodePageResList();
        }).catch(function() {});
      },

      /** 提交保存或修改按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.trackingCodeId !== undefined) {
              updateTrackingCode(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.queryTrackingCodePageResList();
                this.addUpdateOpen = false
              });
            } else {
              //添加防伪码beg
              if (this.batchSaveTracking){
                batchSaveTrackingCode(this.form).then(response => {
                  this.$modal.msgSuccess(response.message)
                  this.queryTrackingCodePageResList();
                  this.addUpdateOpen = false
                });
              }else {
                saveTrackingCode(this.form).then(response => {
                  this.$modal.msgSuccess(response.message)
                  this.queryTrackingCodePageResList();
                  this.addUpdateOpen = false
                });
              }
              //添加防伪码end
            }
          }
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1
        this.queryTrackingCodePageResList()
      },
      /** 重置按钮操作 */
      resetQuery(fromId) {
        this.dateRange = [];
        this.resetForm(fromId);
        this.handleQuery()
      },
      // 取消修改增加弹出层按钮
      cancelAddUpdateOpen() {
        this.addUpdateOpen = false
      },
      // 表单重置
      reset() {
        this.batchSaveTracking = false;
        this.form = {
          trackingCodeId: undefined,
          trackingCode: undefined,
          trackingBatch:undefined,
          transportCode:undefined,
          productId:undefined,
          supplierId:undefined,
          batchTotal: 1,
          statusCode: "",
          statusOptions: []
        };
        this.resetForm('form')
      }
    }
  }
</script>
